#!/usr/bin/env python
"""The code in this module really would fit better elsewhere.
Please pardon me, self, for dumping code here.
"""

from lib.dynamics import Mass, Constraint, Line

#Used by the interface module
def pointOnSegment(Px, Py, Ax, Ay, Bx, By):
    """Tuned for selection purposes
    """
    Vx = Px - Ax
    Vy = Py - Ay
    Cx = Bx - Ax
    Cy = By - Ay
    div = (Cx * Cx + Cy * Cy)
    if div == 0:
        return 0.0, 0.0
    t = (Vx * Cx + Vy * Cy) / div
    if t > 0.8:
        t = 0.8
    if t < 0.2:
        t = 0.2
    return Ax + Cx * t, Ay + Cy * t

def worldDistance(elementList, x, y):
    """Sorts a list of all the world's items by their distance to pos
    """
    distDict = {}
    #Get distance of P to all items
    for element in elementList:
        distDict[elementDistance(element, x, y)] = element
    
    return list(distDict[distance] for distance in sorted(distDict))

def elementDistance(element, x, y):
    """Distance of element to pos
    """
    if element.__class__ == Mass:
        return (element.x - x) ** 2 + (element.y - y) ** 2
    elif element.__class__ == Constraint:
        Px, Py = pointOnSegment(x, y, element.mass1.x, element.mass1.y,
                                         element.mass2.x, element.mass2.y)
        return (Px - x) ** 2 + (Py - y) ** 2
    elif element.__class__ == Line:
        Px, Py = pointOnSegment(x, y, element.p1.x, element.p1.y,
                                         element.p2.x, element.p2.y)
        return (Px - x) ** 2 + (Py - y) ** 2